extends CharacterBody2D

@onready var animations:AnimatedSprite2D = $Animations

@export var followDistance = 16.0

var face = "Down"
var data = null
var followTarget:Node2D  = null
var walkAnimFrameCount = 0
var paths = []
var pathTotalLength = 0


func setFollowTarget(target):
	followTarget = target
	position = followTarget.position


func setData(_data):
	data = _data


func setSpriteFrames(spriteFrames):
	animations.sprite_frames = ResourcePreload.resources[spriteFrames]


func _physics_process(delta):
	processZIndex()
	processFollowTarget(delta)
	

func processFollowTarget(delta):
	if not followTarget: return
	
	if paths.size() <= 0:
		paths.append(followTarget.position)
	else:
		var lastPoint = paths[paths.size() - 1]
		var moveDistance = followTarget.position.distance_to(lastPoint)
		if moveDistance >= Consts.EPSILON:
			paths.append(followTarget.position)
			pathTotalLength = calcTotalPathLength()
			
	if paths.size() > 0 and pathTotalLength > followDistance:
		var nextPoint = paths.pop_front()
		pathTotalLength = calcTotalPathLength()
		var moveDir = (nextPoint - position).normalized()
		
		face = Global.dir2Face(moveDir)
		var animName = "Walk" + face
		if animations.animation != animName:	
			animations.play(animName)
			walkAnimFrameCount = animations.sprite_frames.get_frame_count(animName)
		
		position = nextPoint
	else:
		var animName = "Idle" + face
		if not animations.animation.begins_with("Walk") or animations.frame >= (walkAnimFrameCount - 1):	
			animations.play(animName)
		
				
func processZIndex():
	z_index = int(position.y)
		

func calcTotalPathLength():
	if paths.size() <= 1:
		return 0
	
	var temp = 0
	var lastPoint:Vector2 = paths[0]
	for index in range(1, paths.size()):
		var currentPoint = paths[index]
		temp += lastPoint.distance_to(currentPoint)
		lastPoint = currentPoint
		
	return temp
		
		
	
	
	
